package com.service;

import com.doubao.ChatRequest;
import com.doubao.ChatResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionContentPart;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class DoubaoAiService {

    @Value("${volcengine.api-key}")
    private String apiKey;

    @Value("${volcengine.base-url}")
    private String baseUrl;

    private final ObjectMapper objectMapper;
    private final ArkService arkService;

    public ChatResponse getAnswer(ChatRequest request) {
        ChatResponse response = new ChatResponse();

        try {
            // 构建多内容部分（支持文本和图像）
            List<ChatCompletionContentPart> multiParts = new ArrayList<>();

            // 添加文本内容
            multiParts.add(ChatCompletionContentPart.builder()
                    .type("text")
                    .text(request.getQuestion())
                    .build());

            // 可扩展：如果有图像URL，添加图像内容


            // 构建用户消息
            ChatMessage userMessage = ChatMessage.builder()
                    .role(ChatMessageRole.USER)
                    .multiContent(multiParts)
                    .build();

            // 构建消息列表
            List<ChatMessage> messages = new ArrayList<>();
            messages.add(userMessage);

            // 构建聊天完成请求
            ChatCompletionRequest chatRequest = ChatCompletionRequest.builder()
                    .model("doubao-seed-1-6-flash-250615") // 替换为实际模型
//                    .stream(true)
                    .messages(messages)
                    .temperature(0.7)
                    .maxTokens(2048)
                    .build();

            log.info("请求火山引擎AI: {}", objectMapper.writeValueAsString(chatRequest));

            // 发送请求并处理响应
            String answer = (String) arkService.createChatCompletion(chatRequest)
                    .getChoices()
                    .stream()
                    .findFirst()
                    .map(choice -> choice.getMessage().getContent())
                    .orElse("抱歉，未能获取回答");

            response.setAnswer(answer);
            log.info("火山引擎AI响应: {}", answer);

        } catch (Exception e) {
            log.error("调用火山引擎AI失败", e);
            response.setSuccess(false);
            response.setErrorMessage("调用AI服务失败: " + e.getMessage());
        }

        return response;
    }
}